<template>
<div id="app" class="adOwner">
      <!--广告主筛选-->
  <div class="search">
    <div class="selectOption">
              <el-input v-model="advTitle" placeholder="请输入广告主名称"></el-input>
              <el-cascader v-model="selectedOption" expand-trigger="hover" :options="addressData" clearable  class='el-input' placeholder="按地址检索"> </el-cascader>
              <el-date-picker v-model="value1" type="date" placeholder="选择日期" :editable='false'></el-date-picker>
              <el-button type="primary"  @click='advSearch' class='checkBtn'>检索</el-button>
              <el-button type="success"  @click='addAdvertisers'> 添加广告主</el-button>
    </div>
  </div>  
    <!--广告主列表-->
    <div class="contain_two" style="min-width: 675px;">
      <table class="table table-bordered" style="border-radius: 10px!important;">
        <thead>
          <tr style="height: 40px">
            <th>
              <div class="">
                <span>#</span>
              </div>
            </th>
            <th class=""><span>logo</span></th>

            <th>
              <div class="">
                <span>名称</span>
              </div>
            </th>

            <th><span>区域</span></th>

            <th class=""><span>联系方式</span></th>
            <th class=""><span>邮箱</span></th>
            <th class=""><span>添加时间</span></th>
            <th><span>资质</span></th>
            <th class=""><span>操作</span></th>
          </tr>
        </thead>
        <tbody id="staff_info" class="">
          <tr class="contLi" v-for="(list,index) in tableData">
            <td>
              <div class=""><span class="">{{index+1}}</span></div>
            </td>
            <td class=""><img :src="list.logo" class="" width="25px"></td>
            <td class=""><span class=" ">{{list.name}}</span></td>
            <td class="text-left"><span class=" ">{{list.region}}</span></td>
            <td class=""><span class=" ">{{list.telephone}}</span></td>
            <td class=""><span class=" ">{{list.email}}</span></td>
            <td class=""><span class="add-time">{{list.createDate}}</span></td>
            <td><a><img :src="list.qualification" width="25"></a></td>
            <td class="">
              <el-button type="warning" @click="open2(index)">删除</el-button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="block pagination" v-show='nullContentPagination'>
        <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="10" layout="prev, pager, next, jumper"
          :total="total">
          </el-pagination>
      </div>
      <div class="nullContent" v-show='nullContent'>暂无数据</div>
    <!--添加广告主弹窗-->
    <div class="tankuang" v-show="adverShow">
      <div class="bomb" style="width: 780px;height: 493px;">
        <div class="bomb_header">
          <p>添加广告主</p>
          <span @click="closes"><img src="../../assets/images/icon_tanc_close@2x.png" width="10" height="10"></span>
        </div>
        <div class="bomb_content" style="height:345px;">
          <p style="width: 50%;float: left;position:relative;">
              <span>公司logo：</span>
               <img :src="logoImg" alt="/img/loading.gif" @click="upload"  width="80px" height="80px">
               <span class="egRatio">图片上传尺寸比例为：1:1</span>
               <input id="logofile" type="file" style="display: none" @change="onFileChange" 
               accept="image/jpeg,image/jpg,image/png">
            </p>
            <p style="width: 50%;float: left;">
              <span>广告主资质：</span>
              <img :src="quaImg" alt="/img/loading.gif" width="80px" height="80px" @click="uploads">
              <input type="file" accept="image/jpeg,image/jpg,image/png"
                  name="file" id="logofiles" style="display: none" @change="onFileChanges" />
            </p>
            <div class="clear"></div>
            <p>
              <span>广告主名称：</span>
              <input type="text" v-model="advertiserName" name="" id="1" class="advertiser-name advertiser" maxlength="10" placeholder="请输入广告主名称（最多10个字）">
            </p>
            <p>
              <span style="float: left;line-height: 30px;">广告主所属区域：</span>
              <select v-model="selecteds" @change="chooseMedicines">
                <option v-for="yx in addressData" :value="yx.value" >
                  {{yx.value}}
                </option>
              </select>
              <select v-model="aaaas" style="margin-left: 5px;">
                <option v-for="sss in YXss" :value="sss.value" >
                  {{sss.value}}
                </option>
               </select>
            </p>
            <div class="clear"></div>

            <p>
              <span>广告主电话：</span>
              <input type="text" v-model="telephone" name="" id="" class="advertiser phone" maxlength="11" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')"
                onafterpaste="this.value=this.value.replace(/[^0-9]/g,'')" placeholder="请输入广告主电话">
            </p>
            <p>
              <span>广告主邮箱：</span>
              <input type="text" v-model="email" name="" id="" class="advertiser email" placeholder="请输入广告主邮箱">
            </p>
        </div>
        <div class="bomb_footer">
          <input type="button" @click="addSure" value="保存"> 
          <input type="button" @click="cancels" value="取消"> 
        </div>
      </div>
    </div>

  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
// 导入地址数据
import addressData from '../../assets/js/addressData.js'
// 加载地址数据
function formatData(data) {
  return data
}
export default {
  name: 'adOwner',
  data() {
    return {
       nullContent: false,
       nullContentPagination: true,
      logoImg:'../../../static/img/icon_xinjian_picture@2x.png',
      quaImg:'../../../static/img/icon_xinjian_picture@2x.png',
      advers:'',
      advTitle:'',
      total:0,
      currentPage: 1,
      selected: '请选择',
      selecteds: '请选择',
      aaaa: '请选择',
      aaaas: '请选择',
      YXs: [
        {
          value: '请选择',
        }
      ],
      YXss: [
        {
          value: '请选择',
        }
      ],
      selectedOption:[],
      selectedOptions: [],
      selectedOptionss: [],
      tableData: [],
      addressData: formatData(addressData),
      value1: '',
      adverShow: false,
      showIf:false,
      lists: [],
      advertiserName:'',
      telephone:'',
      email:'',
      imageUrl:'',
      islogoImg:''
    }
  },
  created: function () {
    // 获取广告主列表
    this.getadOwer(1)
  },
  methods: {
    // 提示
    warning:function(){
         this.$message({
          message: '请选择正确图片格式!',
          type: 'warning'
        });
    },
       // 选择图片上传
      onFileChange(e) {
          var self = this
          self.islogoImg = true
          var files = e.target.files || e.dataTransfer.files;
          var fileData  = files[0]
          console.log(fileData,'13')
          //读取图片数据
                var reader = new FileReader();
                reader.onload = function (e) {
                     var data = e.target.result;
                    //加载图片获取图片真实宽度和高度
                     var image = new Image();
                     console.log(image)
                     image.onload=function(){
                         var width = image.width;
                         var height = image.height;
                         if(width !== height){
                           self.warning()
                            return
                         }else{
                           self.uploadImage(files[0]);
                         }
                     };
                     image.src= data;
                 };
                 reader.readAsDataURL(fileData);
      },
      // 上传图片
      uploadImage(file) {
          var formdata = new FormData();
          formdata.append('token', sessionStorage.token);
          formdata.append('appId', "com_sxluckyking_double");
          formdata.append('file', file);
          formdata.append('appName', "appName");
          this.uploadFile(formdata).then((data) => {
              console.log(data);
              if (data.code === 200) {
                   this.$message({
                      message: '上传图片成功',
                      type: 'success'
                    });
                    if(this.islogoImg == true){
                      this.logoImg = data.data[0].path;
                    }else{
                      this.quaImg = data.data[0].path;
                    }
                  
              } else {
                  this.$message.error('上传图片失败');
              }
          }).catch(msg => console.log(msg));
      },
      // 选择图片上传
      onFileChanges(e) {
          this.islogoImg = false
          var files = e.target.files || e.dataTransfer.files;
          this.uploadImage(files[0]);
      },
    chooseMedicine: function () {
      console.log(this.selected)
      var valStr = this.selected;
      var arrs = this.addressData;
      var zys = []
      arrs.forEach(function (ele, index) {
        if (ele.value.indexOf(valStr) > -1) {
          var sss = arrs[index].children
          zys = sss;
        }
      })
      this.YXs = zys;
      this.aaaa = zys[0].value
    },
    chooseMedicines: function () {
      var valStr = this.selecteds;
      var arrs = this.addressData;
      var zys = []
      arrs.forEach(function (ele, index) {
        if (ele.value.indexOf(valStr) > -1) {
          var sss = arrs[index].children
          zys = sss;
        }
      })
      this.YXss = zys;
      this.aaaas = zys[0].value
    },
    addAdvertisers: function () {
      this.logoImg = '../../../static/img/icon_xinjian_picture@2x.png'
      this.quaImg = '../../../static/img/icon_xinjian_picture@2x.png'
      this.adverShow = true;
      this.advertiserName = ''
      this.aaaas = '请选择'
      this.telephone = ''
      this.email = ''
    },
    closes: function () {
      this.adverShow = false;
    },
    Delshow:function(){
      this.showIf =  true
    },
    upload: function () {
      $("#logofile").click();
    },
    uploads: function () {
      $("#logofiles").click();
    },
    cancels: function () {
      this.adverShow = false;
    },
    // 判断
    panduan() {
    var email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var phone = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
    var moble = /^0\d{2,3}-?\d{7,8}$/;
    if (this.logoImg == "../../../static/img/icon_xinjian_picture@2x.png") {
        this.$message("请选择公司logo");
        return false;
    }
    if (this.quaImg == "../../../static/img/icon_xinjian_picture@2x.png") {
        this.$message("请选择广告主资质");
        return false;
    }
    if (this.advertiserName == null || this.advertiserName == "") {
        this.$message("请输入广告主名称");
        return false;
    } else if (this.advertiserName.length > 40) {
        this.$message("广告主名称不可以超过40个字符");
        return false;
    }
    if (this.aaaas == "请选择" || this.aaaas == null) {
        this.$message("请选择广告主所属区域");
        return false;
    }
    if (this.telephone == null || this.telephone == "") {
        this.$message("请输入广告主电话");
        console.log(phone.test(this.phone))
        return false;
    }
    if (!phone.test(this.telephone) && !moble.test(this.telephone)) {
        this.$message("请输入正确的电话号码");
        return false;
    }
    if (this.email == null || this.email == "") {
        this.$message("请输入广告主电子邮箱");
        return false;
    } else if (!email.test(this.email)) {
        this.$message("请输入正确的电子邮箱格");
        return false;
    }
    
    return true;
},
    Del(i){
      this.adOwerDellist({
        id:this.tableData[i].id,
        token:sessionStorage.token
      }).then((data)=>{
          if (data.code === 200) {
            this.getadOwer(this.currentPage)
        } else {
            $this.message('删除失败')
        }
      }).catch(msg => console.log(msg));        
    },
    open2(index) {
      console.log(index)
      console.log(this.tableData[index].id)
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.Del(index)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
     // 请求格式化日期
    UnFormatDate(date) {
        return  new  Date(date).toLocaleString().split(' ')[0].replace(/\//g,'-');
      },
    advSearch(){
      console.log(this.advers)
      var jsonFilter = {};
      if (this.advTitle != "" && this.advTitle != null) {
        jsonFilter.name = this.advTitle;//广告主名称
       }
      if(this.selectedOption != "") {
        jsonFilter.region = this.selectedOption[1];//广告主区域
       }
       if (this.value1 != "" && this.value1 != null) {
        jsonFilter.createDate = this.UnFormatDate(this.value1) + " 00:00:00";//广告创建开始时间
        jsonFilter.endCreateDate = this.UnFormatDate(this.value1) + " 23:59:59";//广告创建结束时间
      }
      this.getadOwerList({
        pageNo: this.currentPage,//当前页码
        pageSize: 10,//总页数
        jsonFilter: JSON.stringify(jsonFilter)
      }).then((data)=>{
        if(data.code == 200){
         this.total = data.data.count;
          for(let i=0;i<data.data.list.length;i++){
                data.data.list[i].logo = data.data.list[i].logo ;
                data.data.list[i].name = data.data.list[i].name ;
                data.data.list[i].region = data.data.list[i].region ;
                data.data.list[i].telephone = data.data.list[i].telephone ;
                data.data.list[i].email = data.data.list[i].email ;
                data.data.list[i].createDate = this.formatDate(data.data.list[i].createDate);
                data.data.list[i].qualification = '' ? '../../../static/img/icon_xinjian_picture@2x.png' : data.data.list[i].qualification ;
        }
          this.tableData = data.data.list
        }else{
          this.$message('error')
        }

      }).catch(msg => console.log(msg))
    },
    // 分页跳转
    handleCurrentChange(val) {
        this.currentPage = val;
        this.getadOwer(val);
    },
    // 格式化日期
    formatDate(date){
          return new Date(parseInt(date)).toLocaleString().replace(/年|月|日/g, "")
    },
    // 广告主页面添加广告主
    addSure(){
        if(this.panduan() == false){
            return
        }else{
        this.adaddOwerlist({
            token:sessionStorage.token,
            logo: this.logoImg,
            name: this.advertiserName,
            region: this.aaaas,
            telephone: this.telephone,
            email: this.email,
            qualification: this.quaImg,
        }).then((data)=>{
            console.log(data)
            if(data.code == 200){
                this.cancels()
                this.getadOwer(this.currentPage)
            }else{
                this.$message('添加广告主失败')
            }
        }).catch(msg => console.log(msg));
        }
    },
    getadOwer(i){
      this.$store.commit('showLoading');
      var jsonFilter = {};
      if (this.advTitle != "" && this.advTitle != null) {
        jsonFilter.name = this.advTitle;//广告主名称
       }
      if(this.selectedOption != "") {
        jsonFilter.region = this.selectedOption[1];//广告主区域
       }
       if (this.value1 != "" && this.value1 != null) {
        jsonFilter.createDate = this.UnFormatDate(this.value1) + " 00:00:00";//广告创建开始时间
        jsonFilter.endCreateDate = this.UnFormatDate(this.value1) + " 23:59:59";//广告创建结束时间
      }
      let token = sessionStorage.token;
      this.getadOwerList({
        pageSize: 10,
        pageNo:i,
        code: 'com_sxluckyking_appManage',
        token:token,
        jsonFilter: JSON.stringify(jsonFilter)
      }).then((data)=>{
        this.$store.commit('hiddenLoading');
        console.log(data)
        if(data.code === 200){
          this.nullContent = false;
          this.nullContentPagination = true;
          if (data.data.list.length == 0) {
              this.nullContent = true;
              this.nullContentPagination = false;
              return;
          }
          this.total = data.data.count;
          for(let i=0;i<data.data.list.length;i++){
                data.data.list[i].logo = data.data.list[i].logo ;
                data.data.list[i].name = data.data.list[i].name ;
                data.data.list[i].region = data.data.list[i].region ;
                data.data.list[i].telephone = data.data.list[i].telephone ;
                data.data.list[i].email = data.data.list[i].email ;
                data.data.list[i].createDate = this.formatDate(data.data.list[i].createDate);
                data.data.list[i].qualification = '' ? '../../../static/img/icon_xinjian_picture@2x.png' : data.data.list[i].qualification ;
        }
          this.tableData = data.data.list
        }else{
          this.$message('error')
        }
      }).catch(msg => console.log(msg));
    },
      ...mapActions(['getadOwerList','adOwerDellist','adaddOwerlist','uploadFile'])
  }
}

</script>
<style scoped>

  .el-date-editor.el-input {
    width: 158px;
  }
  .advertiser select {
    float: left;
    width: 70px;
    height: 36px;
    border-radius: 4px;
    border: 1px solid #bfcbd9;
  }
  
  .areaselect input {
    float: left;
    width: 200px;
    height: 36px;
  }
  
  .add_reward {
    background: rgb(82, 186, 130);
    border-radius: 5px;
    width: 115px;
    height: 36px;
    border: none;
    margin-left: 45px;
    color: #fff;
  }
  
  th,
  td {
    text-align: center;
  }

  .modal-header {
    border-bottom: none;
    border-radius:10px;
  }
  
  .modal-title {
    padding: 10px 0 20px 0;
    color: rgb(109, 148, 189);
    border-bottom: 1px solid #ccc;
    font-weight: 600;
    font-size: 20px;
    text-align: center;
  }
  
  .bomb_content p {
    text-align: left;
    margin: 10px 0;
    float: left;
    width: 100%;
  }
  
  .bomb_content input {
    width: 256px;;
    height: 36px;
    margin-left: 23px;
     border-radius: 4px;
    border: 1px solid #bfcbd9;
  }
  ::-webkit-input-placeholder {
    color:#bfcbd9;  
}  
  
  .bomb_content input[type=file] {
    display: none
  }
  
  .bomb_content img {
    margin-left: 16px;
  }
  
  .egRatio {
    width: 60px;
    top: 0px;
    position: absolute;
    left: 190px;
    color: #a5a3a3;
  }
  
  .bomb_content select{
   float: left;
    width: 93px;
    height: 36px;
    border-radius: 4px;
    border: 1px solid #bfcbd9;
    margin-left: -1px;
  }
  /*饿了么上传文件*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.el-upload input[type=file]{display: none!important;}
table th{
    padding:0;
    height: 40px;
    line-height: 40px;
}
.table > tbody > tr{
    padding:0;
}

.el-input {
        width: 200px;
    }
.el-button--success{
    width: 96px;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload img{
    overflow: hidden;
  }
  .adOwner{
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: 5px;
  }
</style>